/**
 * 
 */
package com.hst.web.common.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hst.core.ServiceContext;
import com.hst.core.annotation.WebAuth;
import com.hst.core.dao.IDService;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.User;
import com.hst.web.sys.entity.TUser;

/**
 * @author wangyh
 *
 */

@Controller
@RequestMapping("/upload")
public class UploadController {

	String fold = "../filestore";

	@Autowired
	IDService id;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/{t}", method = RequestMethod.POST)
	@ResponseBody()
	void upload(@PathVariable String t, @RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User) ServiceContext.getInstance().getUser();
		if (user == null) {
			String strAuthorization = request.getHeader("authorization");
			if (strAuthorization == null || strAuthorization.indexOf("Bearer") < 0) {
				return;
			}
		}
		String name = getFileName(t, file.getOriginalFilename());
		name = generatePathName(name);

		File f = new File(fold + name);
		f.getParentFile().mkdirs();
		FileUtils.copyInputStreamToFile(file.getInputStream(), f);
		// file.getFileItem().write(f);
		Map<String, String> m= new HashMap();
		m.put("status", "1");
		m.put("name", name);
		
		response.setContentType("text/plan;chartset=UTF8");
		response.getWriter().write(JsonUtil.toString(m));
	}

	@RequestMapping(value = "/{t}/{name}")
	@ResponseBody
	void download(@PathVariable String t, @PathVariable String name, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		User user = (User) ServiceContext.getInstance().getUser();
		if (user == null) {
			String strAuthorization = request.getHeader("authorization");
			if (strAuthorization == null || strAuthorization.indexOf("Bearer") < 0) {
				return;
			}
		}
		// String fileName = request.getPathInfo().substring(7);
		String fileName = name;
		File f = new File(fold + t + "/" + fileName);
		try (InputStream bis = new BufferedInputStream(new FileInputStream(f))) {
			try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
				IOUtils.copy(bis, bos);
			}
		}
	}

	String getFileName(String t, String fileName) {
		String sidName = "file-" + t;
		String sid = id.formatCode(10, id.getCode(sidName, true), true, "");

		int p = fileName.lastIndexOf('.');
		String ext = p > -1 ? fileName.substring(p) : ".";

		return t + "/" + sid + ext;
	}

	@RequestMapping(value = "/{t}/{folder}/{name:.+}")
	@ResponseBody
	void downloadImg(@PathVariable String t, @PathVariable String folder, @PathVariable String name,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User) ServiceContext.getInstance().getUser();
		if (user == null) {
			String strAuthorization = request.getHeader("authorization");
			//System.out.println("strAuthorization:=" + strAuthorization + ";");
			if (strAuthorization == null || strAuthorization.indexOf("Bearer") < 0) {
				return;
			}
		}
		download(t, folder + "/" + name, request, response);
	}
	
	@RequestMapping(value = "/{t}/{folder}/{folder1}/{name:.+}")
	@ResponseBody
	void downloadImg(@PathVariable String t, @PathVariable String folder,@PathVariable String folder1, @PathVariable String name,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User) ServiceContext.getInstance().getUser();
		if (user == null) {
			String strAuthorization = request.getHeader("authorization");
			//System.out.println("strAuthorization:=" + strAuthorization + ";");			
			if (strAuthorization == null || strAuthorization.indexOf("Bearer") < 0) {
				return;
			}
		}
		download(t, folder + "/" + folder1 + "/" + name, request, response);
	}

	DateFormat df = new SimpleDateFormat("yyyyMMdd");

	/**
	 * 加日期文件夹
	 * 
	 * @param path
	 * @return
	 */
	String generatePathName(String path) {
		int i = path.lastIndexOf("/");
		path = path.substring(0, i + 1) + df.format(new Date()) + "/" + path.substring(i + 1);
		return path;
	}
}
